<template>
    <div class="article-edit">
        <el-card class="edit-card">
            <template #header>
                <div class="card-header">
                    <div class="header-left">
                        <el-button link @click="goBack">
                            <el-icon>
                                <ArrowLeft />
                            </el-icon>返回
                        </el-button>
                        <span class="title">{{ isEdit ? '编辑文章' : '写文章' }}</span>
                    </div>
                    <div class="header-right">
                        <el-button @click="saveDraft">保存草稿</el-button>
                        <el-button type="primary" @click="publish">发布</el-button>
                    </div>
                </div>
            </template>

            <el-form ref="formRef" :model="articleForm" :rules="rules" label-width="80px">
                <el-form-item label="标题" prop="title">
                    <el-input v-model="articleForm.title" placeholder="请输入文章标题"></el-input>
                </el-form-item>

                <el-form-item label="分类" prop="category">
                    <el-select v-model="articleForm.category" placeholder="请选择分类">
                        <el-option v-for="item in categories" :key="item.id" :label="item.name"
                            :value="item.name"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="标签" prop="tags">
                    <el-select v-model="articleForm.tags" multiple filterable allow-create placeholder="请选择标签">
                        <el-option v-for="item in tags" :key="item.id" :label="item.name"
                            :value="item.name"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="摘要" prop="summary">
                    <el-input v-model="articleForm.summary" type="textarea" :rows="3" placeholder="请输入文章摘要"></el-input>
                </el-form-item>

                <div class="form-row">
                    <el-form-item label="封面" prop="cover" class="cover-item">
                        <el-alert title="封面上传功能暂未开放" type="info" :closable="false" class="mb-10" />
                        <div class="cover-placeholder">
                            <el-icon class="placeholder-icon">
                                <Picture />
                            </el-icon>
                            <span class="placeholder-text">封面图片</span>
                        </div>
                    </el-form-item>

                    <el-card class="access-control" shadow="hover">
                        <div class="control-header">
                            <span class="control-title">文章加密</span>
                            <el-switch v-model="articleForm.isEncrypted" />
                        </div>
                        <el-collapse-transition>
                            <div v-if="articleForm.isEncrypted" class="password-section">
                                <el-input v-model="articleForm.password" type="password" placeholder="请设置文章访问密码"
                                    show-password>
                                    <template #prefix>
                                        <el-icon>
                                            <Lock />
                                        </el-icon>
                                    </template>
                                </el-input>
                                <div class="password-tip">
                                    <el-icon>
                                        <InfoFilled />
                                    </el-icon>
                                    <span>设置密码后，访问者需要输入密码才能查看文章内容</span>
                                </div>
                            </div>
                        </el-collapse-transition>
                    </el-card>
                </div>

                <el-form-item label="内容" prop="content" class="content-item">
                    <MdEditor v-model="articleForm.content" :preview="true" theme="light" height="500px"
                        :upload-images="handleUploadImage" :image-config="{
                            max: 5 * 1024 * 1024,  // 限制图片大小为5MB
                            accept: ['jpg', 'jpeg', 'png', 'gif', 'webp'],  // 允许的图片格式
                        }" />
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { Plus, ArrowLeft, Picture, Lock, InfoFilled } from '@element-plus/icons-vue'
import articleApi from '@/api/article'
import { MdEditor } from 'md-editor-v3'
import 'md-editor-v3/lib/style.css'
import axios from 'axios'

const route = useRoute()
const router = useRouter()
const formRef = ref<FormInstance>()
const isEdit = ref(false)
const theme = ref('light')

// 表单数据
const articleForm = reactive({
    title: '',
    category: '',
    tags: [] as string[],
    summary: '',
    cover: '',
    content: '',
    status: 'draft' as 'published' | 'draft',
    isEncrypted: false,
    password: ''
})

// 表单验证规则
const rules = reactive<FormRules>({
    title: [
        { required: true, message: '请输入文章标题', trigger: 'blur' },
        { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
    ],
    category: [
        { required: true, message: '请选择文章分类', trigger: 'change' }
    ],
    content: [
        { required: true, message: '请输入文章内容', trigger: 'blur' }
    ]
})

// 分类列表
const categories = ref([
    { id: 1, name: '技术' },
    { id: 2, name: '生活' }
])

// 标签列表
const tags = ref([
    { id: 1, name: 'Vue' },
    { id: 2, name: 'TypeScript' },
    { id: 3, name: '随' }
])

// 上传地址
const uploadUrl = import.meta.env.VITE_API_URL + '/upload'

// 获取文章详情
const getArticleDetail = async (id: number) => {
    try {
        const res = await articleApi.getDetail(id)
        if (res.code === 200) {
            Object.assign(articleForm, res.data)
        }
    } catch (error) {
        console.error('获取文章详情失败:', error)
        ElMessage.error('获取文章详情失败')
    }
}

// 保存文章
const saveArticle = async (status: 'published' | 'draft') => {
    if (!formRef.value) return

    await formRef.value.validate(async (valid) => {
        if (valid) {
            try {
                articleForm.status = status
                const id = route.params.id as string
                const res = isEdit.value
                    ? await articleApi.update(parseInt(id), articleForm)
                    : await articleApi.create(articleForm)

                if (res.code === 200) {
                    ElMessage.success(status === 'published' ? '发布成功' : '保存成功')
                    router.push('/admin/article/list')
                }
            } catch (error) {
                console.error('保存文章失败:', error)
                ElMessage.error('保存失败')
            }
        }
    })
}

// 保存草稿
const saveDraft = () => {
    saveArticle('draft')
}

// 发布文章
const publish = () => {
    saveArticle('published')
}

// 封面上传成功
const handleCoverSuccess = (res: any) => {
    articleForm.cover = res.data.url
}

// 封面上传前的验证
const beforeCoverUpload = (file: File) => {
    const isImage = file.type.startsWith('image/')
    const isLt2M = file.size / 1024 / 1024 < 2

    if (!isImage) {
        ElMessage.error('只能上传图片文件!')
    }
    if (!isLt2M) {
        ElMessage.error('图片大小不能超过 2MB!')
    }

    return isImage && isLt2M
}

// 返回列表页
const goBack = () => {
    router.push('/admin/article/list')
}

// 图片上传处理函数
const handleUploadImage = async (files: FileList, callback: (urls: string[]) => void) => {
    const formData = new FormData()
    Array.from(files).forEach(file => {
        formData.append('file', file)
    })

    try {
        const response = await axios({
            method: 'post',
            url: uploadUrl,
            data: formData,
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        })

        if (response.data.code === 200) {
            callback([response.data.data.url])
        } else {
            ElMessage.error('图片上传失败')
        }
    } catch (error) {
        console.error('上传图片失败:', error)
        ElMessage.error('图片上传失败')
    }
}

onMounted(() => {
    const id = route.params.id
    if (id) {
        isEdit.value = true
        getArticleDetail(parseInt(id as string))
    }
})
</script>

<style scoped>
.article-edit {
    width: 100%;
    height: 100%;
    padding: 20px;
}

.edit-card {
    min-height: calc(100vh - 140px);
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.header-left {
    display: flex;
    align-items: center;
    gap: 10px;
}

.header-left .title {
    font-size: 16px;
    font-weight: 500;
}

.header-right {
    display: flex;
    gap: 10px;
}

.form-row {
    display: grid;
    grid-template-columns: 240px 320px;
    gap: 20px;
    margin-bottom: 20px;
    /* align-items: flex-end; */
}

.cover-placeholder {
    width: 100%;
    height: 160px;
    border: 1px dashed var(--el-border-color);
    border-radius: 8px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: var(--el-text-color-secondary);
    background-color: var(--el-fill-color-lighter);
}

.placeholder-icon {
    font-size: 32px;
    margin-bottom: 8px;
}

.placeholder-text {
    font-size: 14px;
}

.mb-10 {
    margin-bottom: 10px;
}

.access-control {
    /* height: 160px; */
    margin-bottom: 0;
}

.access-control :deep(.el-card__body) {
    height: 100%;
    padding: 16px;
    display: flex;
    flex-direction: column;
}

.control-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 16px;
}

.control-title {
    font-size: 14px;
    color: var(--el-text-color-regular);
}

.password-section {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 8px;
    padding-top: 16px;
    border-top: 1px solid var(--el-border-color-lighter);
}

.password-tip {
    display: flex;
    align-items: flex-start;
    gap: 4px;
    color: var(--el-text-color-secondary);
    font-size: 12px;
    line-height: 1.5;
}

.password-tip .el-icon {
    margin-top: 3px;
    font-size: 12px;
    color: var(--el-color-info);
}

.content-item {
    margin-bottom: 0;
}

:deep(.md-editor) {
    border: 1px solid var(--el-border-color);
    border-radius: 4px;
}

:deep(.md-editor-dark) {
    --md-bk-color: var(--el-bg-color);
}

.cover-item,
.control-item {
    margin-bottom: 0;
}
</style>